<?php
class AccountController extends Zend_Controller_Action
{
	public function registerAction()
	{
		$auth = Blogger_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$this->view->identity = $auth->getIdentity();
			$this->_helper->redirector('index', 'dashboard');
			return;
		}
		$signupForm = new Application_Form_Signup();
		$request = $this->getRequest();
		$this->view->registerSuccess = 0;
		if($request->isPost())
		{
			if($signupForm->isValid($request->getPost()))
			{
				$users = new Blogger_Users();
				$users->register($signupForm->getValue('fname'),
									$signupForm->getValue('lname'),
									$signupForm->getValue('email'),
									$signupForm->getValue('password'),
									$signupForm->getValue('alias')
									);
				$this->view->registerSuccess = 1;
			}
		}
		$this->view->signupForm = $signupForm;
	}
	
	public function loginAction()
	{
		$auth = Blogger_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$this->view->identity = $auth->getIdentity();
			$this->_helper->redirector('index', 'dashboard');
			return;
		}
		$request = $this->getRequest();
		$loginForm = new Application_Form_Login();
		if($request->isPost())
		{
			if($loginForm->isValid($request->getPost()))
			{
				//proceed to authenticate
				$adapter = new Blogger_Auth_Adapter($loginForm->getValue('email'), $loginForm->getValue('password'));
				$result = $auth->authenticate($adapter);
				if(!$result->isValid())
				{
					if(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND == $result->getCode())
						throw new Blogger_Exception('Username not found', Blogger_Exception_Codes::ERROR_USER_SHOWABLE);
					elseif(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID == $result->getCode())
						throw new Blogger_Exception('Invalid password', Blogger_Exception_Codes::ERROR_USER_SHOWABLE);
					else
						throw new Blogger_Exception('User auth failed');
				}
				else
				{
					$this->view->identity = $auth->getIdentity();
					$this->_helper->redirector('index', 'dashboard');
					return;
				}
			}
		}
		$this->view->loginForm = $loginForm;
	}
	
	public function logoutAction()
	{
		$auth = Blogger_Auth::getInstance();
		if($auth->hasIdentity())
		{
			$auth->clearIdentity();
		}
		$this->_helper->redirector('index', 'index');
	}
}